package top.jybill.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import top.jybill.dao.IAccountDao;
import top.jybill.domain.Account;
import top.jybill.utils.ConnectionUtils;

import java.util.List;

public class AccountDaoImpl implements IAccountDao {
  private QueryRunner runner;
  private ConnectionUtils connectionUtils;

  public void setConnectionUtils(ConnectionUtils connectionUtils) {
    this.connectionUtils = connectionUtils;
  }

  public void setRunner(QueryRunner runner) {
    this.runner = runner;
  }

  public List<Account> findAll() {
    List<Account> accounts = null;
    try {
      accounts = runner.query(connectionUtils.getThreadConnection(), "select * from spring_account",
              new BeanListHandler<Account>(Account.class));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return accounts;
  }

  public Account findAccountById(Integer id) {
    Account account = null;
    try {
      account = runner.query(connectionUtils.getThreadConnection(),"select * from spring_account where id = ?", id,
              new BeanHandler<Account>(Account.class));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return account;
  }

  public void updateAccount(Account account) {
    try {
      runner.update(connectionUtils.getThreadConnection(),"update spring_account set name=?, money=? where id = ?",
              account.getName(), account.getMoney(), account.getId());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void insertAccount(Account account) {
    try {
      runner.update(connectionUtils.getThreadConnection(),"insert into spring_account(name, money) values(?, ?)",
              account.getName(), account.getMoney());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void delAccount(Integer id) {
    try {
      runner.update(connectionUtils.getThreadConnection(),"selete from spring_account where id = ?", id);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public Account findAccountByName(String name) {
    List<Account> account = null;
    try {
      account = runner.query(connectionUtils.getThreadConnection(),"select * from spring_account where name = ?", name,
              new BeanListHandler<Account>(Account.class));
      if (account == null || account.size() < 1) {
        return null;
      } else if (account.size() > 1) {
        throw new RuntimeException("获取到多个Account对象异常");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return account.get(0);
  }
}
